<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人博客</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style data-page-style="index">
        :root {
            --primary-color: #2563eb; /* 技术蓝主色 */
            --primary-light: rgba(37, 99, 235, 0.1); /* 主色浅色背景 */
            --secondary-color: #475569; /* 深灰辅助色 */
            --text-primary: #1e293b; /* 主要文字 */
            --text-secondary: #64748b; /* 次要文字 */
            --border-color: #e2e8f0; /* 边框色 */
            --card-shadow: 0 5px 15px rgba(0,0,0,0.05);
            --card-shadow-hover: 0 10px 25px rgba(0,0,0,0.1);
        }

        body {
            background-color: #f1f5f9; /* 更专业的浅灰背景 */

            position: relative;
            color: var(--text-primary);
            font-family: 'Inter', 'Segoe UI', system-ui, sans-serif;
            line-height: 1.7;
        }

        /* 背景图片样式 - 保持原有功能 */
        .bg-image {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            opacity: 0.9; /* 降低透明度，避免干扰内容阅读 */
            transition: opacity 0.5s ease;
        }

        /* 导航栏样式使用全局片段，页面不再覆盖 */

        /* 可调：首页整体内容宽度（变小则卡片更窄） */
        .page-container {
            max-width: 2000px; /* 可调 */
        }

        /* 修复：文章列表位于 .container-fluid.main-content 内，此处需限宽与居中 */
        .main-content {
            max-width: 1000px; /* 可调：与上保持一致 */
            margin: 28px auto 0; /* 顶部留白 + 居中 */
        }

        @media (min-width: 992px) {
            /* 可调：右侧安全区，避免遮挡右下角人偶 */
            .page-container {
                padding-right: 140px; /* 可调 */
            }
            /* 修复：为 .main-content 同步右侧安全区，避免遮挡 */
            .main-content {
                padding-right: 140px; /* 可调 */
            }
        }

        /* 页面标题区优化 */
        .page-header {
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
        }

        .page-header h1 {
            font-size: 1.8rem;
            font-weight: 600;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* 瀑布流布局容器 - 调整为响应式布局 */
        .post-container {
            column-count: 1; /* 默认单列 */
            column-gap: 30px; /* 列间距（可调：增大则更稀疏） */
        }

        @media (min-width: 992px) {
            /* 可调：首页卡片列数（列数越多，单卡越窄） */
            .post-container {
                column-count: 2; /* 可改为 3/4 */
            }
        }

        /* 文章卡片优化 - 固定浅色主题，不受其他页面深色主题影响 */
        .post-card {
            margin-bottom: 30px;
            border: 1px solid #e2e8f0 !important; /* 固定浅色边框 */
            border-radius: 12px;
            overflow: hidden;
            transition: transform 0.3s, box-shadow 0.3s;
            background-color: white !important; /* 强制白色背景 */
            box-shadow: 0 5px 15px rgba(0,0,0,0.05) !important; /* 固定浅色阴影 */
            display: inline-block;
            width: 100%;
            cursor: pointer;
        }

        .post-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1) !important; /* 固定浅色悬停阴影 */
            border-color: transparent;
        }

        /* 文章图片区域 */
        .post-image {
            height: 200px;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            position: relative;
        }

        /* 分类标签 */
        .post-category {
            position: absolute;
            top: 15px;
            left: 15px;
            background-color: var(--primary-color);
            color: white;
            padding: 3px 10px;
            border-radius: 4px;
            font-size: 0.8rem;
            display: flex;
            align-items: center;
            gap: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .post-content {
            padding: 22px;
            background-color: white !important; /* 强制白色背景 */
        }

        .post-title {
            margin-bottom: 12px;
            font-weight: 600;
            font-size: 1.3rem;
        }

        .post-title a {
            color: #1e293b !important; /* 固定深色文字 */
            text-decoration: none;
            transition: color 0.2s;
        }

        .post-title a:hover {
            color: #2563eb !important; /* 固定蓝色悬停 */
        }

        .post-summary {
            color: #64748b !important; /* 固定次要文字颜色 */
            margin-bottom: 18px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            font-size: 0.95rem;
            line-height: 1.6;
        }

        .post-date {
            color: #64748b !important; /* 固定次要文字颜色 */
            font-size: 0.85rem;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        /* 按钮样式优化 */
        .btn-outline-primary {
            color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-outline-primary:hover {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-outline-secondary {
            color: var(--secondary-color);
            border-color: var(--secondary-color);
        }

        .btn-outline-secondary:hover {
            background-color: var(--secondary-color);
            color: white;
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-primary:hover {
            background-color: #1d4ed8;
            border-color: #1d4ed8;
        }

        /* 无文章状态样式 - 固定浅色主题 */
        .no-posts {
            text-align: center;
            padding: 60px 30px;
            background-color: white !important; /* 强制白色背景 */
            border-radius: 12px;
            border: 1px solid #e2e8f0 !important; /* 固定浅色边框 */
            margin-bottom: 30px;
        }

        .no-posts i {
            font-size: 3rem;
            color: #64748b !important; /* 固定次要文字颜色 */
            margin-bottom: 1rem;
        }

        .no-posts h3 {
            color: #1e293b !important; /* 固定主要文字颜色 */
            margin-bottom: 0.5rem;
        }

        .no-posts p {
            color: #64748b !important; /* 固定次要文字颜色 */
        }

        /* 提示框样式优化 */
        .alert {
            margin-bottom: 25px;
            border-radius: 8px;
            border: none;
            padding: 12px 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .alert-success {
            background-color: #dcfce7;
            color: #166534;
        }

        .alert-danger {
            background-color: #fee2e2;
            color: #b91c1c;
        }

        /* 响应式设计 - 保持原有逻辑 */
        @media (max-width: 768px) {
            .post-container {
                column-count: 1;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .nav-link {
                padding: 0.4rem 0.6rem !important;
            }
        }
    </style>
    <script defer src="https://cdn.jsdelivr.net/npm/@hotwired/turbo@7.3.0/dist/turbo.es2017-umd.min.js"></script>
    <script defer src="/js/turbo-fixes.js"></script>
</head>
<body>
<div class="bg-image" th:if="${backgroundImage != null and !backgroundImage.isEmpty()}" th:style="|background-image: url(${backgroundImage});|"></div>

<div th:replace="~{fragments/navbar :: navbar}"></div>

<div class="container-fluid main-content">
    <div class="container page-container mb-3" sec:authorize="hasRole('ADMIN')">
        <a href="/posts/new" class="btn btn-primary">
            <i class="bi bi-plus-circle"></i> 创建新文章
        </a>
    </div>

    <div class="container page-container"> <div class="alert alert-success alert-dismissible fade show" th:if="${message}" role="alert">
        <i class="bi bi-check-circle-fill"></i> <span th:text="${message}"></span>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
        <div class="alert alert-danger alert-dismissible fade show" th:if="${error}" role="alert">
            <i class="bi bi-exclamation-triangle-fill"></i> <span th:text="${error}"></span>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    </div>


    <div class="row gx-4 justify-content-center">
        <div class="col-lg-12 col-md-12"> <div> <div th:if="${!posts.empty}">
            <div class="post-container">
                <div class="post-card" th:each="post : ${posts}" style="cursor: pointer;" th:onclick="'window.location.href=\'/posts/' + ${post.id} + '\''">
                    <div class="post-image" th:if="${post.coverImageUrl != null and !post.coverImageUrl.isEmpty()}"
                         th:style="|background-image: url(${post.coverImageUrl})|">
                                     <span class="post-category" th:if="${post.category != null}">
                                        <i class="bi" th:classappend="${post.category.icon != null ? 'bi-' + post.category.icon : 'bi-tag-fill'}"></i>
                                        <span th:text="${post.category.name}">分类</span>
                                    </span>
                    </div>

                    <div class="post-content">
                        <h2 class="post-title">
                            <a th:href="@{/posts/{id}(id=${post.id})}" th:text="${post.title}">文章标题</a>
                        </h2>
                        <p class="post-summary" th:text="${post.summary != null ? post.summary : '暂无摘要'}">文章摘要...</p>
                        <p class="post-date">
                            <i class="bi bi-calendar3"></i>
                            <span th:text="${#temporals.format(post.createdAt, 'yyyy-MM-dd')}">发布日期</span>
                        </p>
                        <div class="d-flex justify-content-end align-items-center mt-2" sec:authorize="hasRole('ADMIN')">
                            <a th:href="@{/posts/{id}/edit(id=${post.id})}" class="btn btn-sm btn-outline-secondary me-2">
                                <i class="bi bi-pencil"></i> 编辑
                            </a>
                            <button class="btn btn-sm btn-outline-danger"
                                    th:onclick="'event.stopPropagation(); if(confirm(\'确定要删除这篇文章吗？\')) { document.getElementById(\'delete-form-' + ${post.id} + '\').submit(); }'">
                                <i class="bi bi-trash"></i> 删除
                            </button>
                            <form th:id="'delete-form-' + ${post.id}" th:action="@{/posts/{id}/delete(id=${post.id})}" method="post" style="display:none;"></form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
            <div class="no-posts" th:if="${posts.empty}">
                <i class="bi bi-journal-x"></i>
                <h3>暂无文章</h3>
                <p th:if="${activeCategory != null}">该分类下暂无文章</p>
                <p th:unless="${activeCategory != null}" sec:authorize="hasRole('ADMIN')">点击上方"创建新文章"按钮开始写作吧！</p>
            </div>
        </div>
        </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- Live2D 已改为全局初始化，移除本地容器和脚本 -->

<script>
(function() {
    function initChatbot() {
        const chatMessages = document.getElementById('chat-messages');
        const chatInput = document.getElementById('chat-input');
        const sendButton = document.getElementById('send-button');
        if (!chatMessages || !chatInput || !sendButton) return; // 片段未加载，不执行

        // 避免重复绑定
        if (sendButton.dataset.bound === '1') return;

        // 保持对话历史在多次初始化之间可复用
        const conversation = window.__chatConversation || [];
        window.__chatConversation = conversation;

        function displayMessage(text, sender) {
            const messageElement = document.createElement('div');
            messageElement.classList.add('chat-message', sender === 'user' ? 'user-message' : 'bot-message');
            messageElement.innerHTML = (text || '').replace(/\n/g, '<br>');
            chatMessages.appendChild(messageElement);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        async function sendMessage() {
            const messageText = chatInput.value.trim();
            if (messageText === '') return;
            displayMessage(messageText, 'user');
            chatInput.value = '';

            const thinkingElement = document.createElement('div');
            thinkingElement.classList.add('chat-message', 'bot-message', 'thinking');
            thinkingElement.innerHTML = '思考中...';
            chatMessages.appendChild(thinkingElement);
            chatMessages.scrollTop = chatMessages.scrollHeight;

            conversation.push({ role: 'user', content: messageText });

            try {
                const resp = await fetch('/api/assistant/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message: messageText, messages: conversation })
                });
                const data = await resp.json();
                chatMessages.removeChild(thinkingElement);
                if (data && data.success && data.reply) {
                    conversation.push({ role: 'assistant', content: data.reply });
                    displayMessage(data.reply, 'bot');
                } else {
                    const err = (data && data.error) ? data.error : '接口返回异常';
                    displayMessage('抱歉，回答失败：' + err, 'bot');
                }
            } catch (e) {
                chatMessages.removeChild(thinkingElement);
                displayMessage('抱歉，接口调用失败：' + (e && e.message ? e.message : e), 'bot');
            }
        }

        // 事件绑定（按需且只绑定一次）
        sendButton.addEventListener('click', sendMessage);
        chatInput.addEventListener('keydown', function(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        });
        sendButton.dataset.bound = '1';
        chatInput.dataset.bound = '1';

        // 初始欢迎消息仅添加一次
        if (!chatMessages.dataset.welcomed) {
            displayMessage('你好！我是本博客的 AI 助手，可以回答关于文章内容以及其他基本的问题。', 'bot');
            chatMessages.dataset.welcomed = '1';
        }
    }

    // 支持 Turbo 与常规加载
    document.addEventListener('turbo:load', initChatbot);
    if (document.readyState === 'loading') {
        window.addEventListener('DOMContentLoaded', initChatbot);
    } else {
        initChatbot();
    }
})();
</script>

<style>
    #ai-chatbot-container {
        position: sticky; /* 固定在视口中 */
        top: 80px; /* 距离导航栏下方一点距离 */
        height: calc(100vh - 100px); /* 高度，留出上下边距 */
        max-height: 700px; /* 最大高度 */
        display: flex;
        flex-direction: column;
        background-color: #1e1e1e; /* 深色背景 */
        border: 1px solid rgba(102, 178, 255, 0.2); /* 边框 */
        border-radius: 12px;
        overflow: hidden; /* 防止内容溢出 */
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        color: #e0e0e0; /* 浅色文字 */
    }

    .chatbot-header {
        background-color: rgba(102, 178, 255, 0.1);
        color: #66b2ff;
        padding: 12px 15px;
        font-weight: bold;
        border-bottom: 1px solid rgba(102, 178, 255, 0.2);
        display: flex;
        align-items: center;
        gap: 8px;
    }

    #chat-messages {
        flex-grow: 1; /* 占据剩余空间 */
        overflow-y: auto; /* 允许垂直滚动 */
        padding: 15px;
        display: flex;
        flex-direction: column;
        gap: 10px; /* 消息间距 */
        scrollbar-width: thin;
        scrollbar-color: rgba(102,178,255,0.6) rgba(255,255,255,0.08);
    }
    #chat-messages::-webkit-scrollbar { width: 8px; }
    #chat-messages::-webkit-scrollbar-track { background: rgba(255,255,255,0.05); border-radius: 4px;}
    #chat-messages::-webkit-scrollbar-thumb { background-color: rgba(102,178,255,0.45); border-radius: 4px; border: 2px solid transparent; background-clip: content-box; }
    #chat-messages::-webkit-scrollbar-thumb:hover { background-color: rgba(102,178,255,0.65); }


    .chat-message {
        padding: 10px 15px;
        border-radius: 10px;
        max-width: 85%;
        word-wrap: break-word; /* 自动换行 */
        line-height: 1.5;
    }

    .user-message {
        background-color: #66b2ff; /* 用户消息用蓝色 */
        color: #1e293b; /* 深色文字 */
        align-self: flex-end; /* 用户消息靠右 */
        border-bottom-right-radius: 2px;
    }

    .bot-message {
        background-color: #334155; /* AI 消息用灰色 */
        color: #e0e0e0;
        align-self: flex-start; /* AI 消息靠左 */
        border-bottom-left-radius: 2px;
    }
    .bot-message.thinking {
        font-style: italic;
        color: #aaa;
    }


    #chat-input-area {
        display: flex;
        padding: 10px;
        border-top: 1px solid rgba(102, 178, 255, 0.2);
        background-color: #252a33; /* 输入区背景稍深 */
    }

    #chat-input {
        flex-grow: 1;
        background-color: #2d333b;
        color: #e0e0e0;
        border: 1px solid #444c56;
        border-radius: 6px;
        padding: 10px;
        resize: none; /* 禁止拖拽调整大小 */
        height: 60px; /* 固定初始高度 */
        max-height: 120px; /* 限制最大高度 */
        overflow-y: auto; /* 内容多时允许滚动 */
        scrollbar-width: thin;
        scrollbar-color: rgba(102,178,255,0.6) rgba(255,255,255,0.08);
    }
    #chat-input::-webkit-scrollbar { width: 6px;}
    #chat-input::-webkit-scrollbar-thumb { background-color: rgba(102,178,255,0.45); border-radius: 3px; }

    #chat-input:focus {
        outline: none;
        border-color: #66b2ff;
        box-shadow: 0 0 0 0.2rem rgba(102, 178, 255, 0.25);
    }

    #send-button {
        background-color: #66b2ff;
        color: #1e293b;
        border: none;
        border-radius: 6px;
        padding: 0 15px;
        margin-left: 10px;
        cursor: pointer;
        transition: background-color 0.2s;
    }

    #send-button:hover {
        background-color: #5095db;
    }
    #send-button i {
        font-size: 1.2rem;
    }
</style>

<div th:replace="~{fragments/ai_chatbot :: chatbot}"></div>

</body>
</html>